package com.lv.service.dialog

import android.content.Context
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SnackbarUtils.dismiss
import com.github.gzuliyujiang.wheelpicker.widget.LinkageWheelLayout
import com.lihang.ShadowLayout
import com.lv.common.im.OnPositionMoreCancle
import com.lv.common.imp.OnPositionMore
import com.lv.common.imp.OnPositionTListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.Constants.pageSize
import com.lv.common.utils.MyUtils
import com.lv.common.utils.showToast
import com.lv.service.R
import com.lv.service.adapter.CardCategoryImageBottomAdapter
import com.lv.service.bean.CategoryPeriodsDataBean
import com.lv.service.bean.TelSecondCategory
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.CategoryPeriodsBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.room.category.CategoryBean
import com.lv.service.utils.YgxToolsKt
import com.lv.service.weidget.picker.ThirdLikeProvider
import com.lxj.xpopup.core.BottomPopupView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class PeroidCategoryImageSelectedPopupView(
    private val mContext: Context,
    private val mAllBeans: List<CategoryBean>?,
    private var mWheelPosition1: Int = 0,
    private var mWheelPosition2: Int = 0,
    private var mIsOpen: Boolean = false,
    private val mAllCategory: List<TelSecondCategory>? = null,
    private val selectedCategorys: List<TelSecondCategory>? = null,
    private val viewModel: ServiceViewModel?,
    private val mCpyid: String?,
    private val mOtherid: String?,
    private val mIsEditro: Boolean = false,//是否为编辑
    private val mBeans: List<CategoryPeriodsBody>?,//已经存在的期数分类信息
    private var onPopSureListener: OnPositionMore<List<TelSecondCategory>>?
) :
    BottomPopupView(mContext), OnClickListener {
    private val MAXA_SELECTED = 5
    private var maxSelected = 1
    private var mPosition = 0
    private val name = ""
    private var mTab = 0

    //标记进入时的省份、期数位置，用来判断是否修改了省份期数
    private var mWheelTemPosition1: Int = 0
    private var mWheelTemPosition2: Int = 0
    private var mProvince = ""
    private var mPeriod = ""
    private var rvContent: RecyclerView? = null
    private var viewTop: View? = null
    private var viewPeroidTab: View? = null
    private var viewCategoryTab: View? = null
    private var viewBottom: View? = null
    private var vSumbit: View? = null
    private var tvSubmit: TextView? = null
    private var tvPeroidTab: TextView? = null
    private var tvPro: TextView? = null
    private var tvCategoryTab: TextView? = null
    private var tvNext: TextView? = null
    private var mLlCategory: LinearLayout? = null
    private var mViewShadow: ShadowLayout? = null
    private val mCategorys = mutableListOf<TelSecondCategory>()
    private var wheelLinkage: LinkageWheelLayout? = null
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    private val mSelectedCategorys = mutableListOf<TelSecondCategory>()
    private var mOnPopSwitchListener: OnPositionTListener<Int>? = null

    private var mAdapter: CardCategoryImageBottomAdapter? = null
    override fun getImplLayoutId(): Int {
        return R.layout.peroid_category_image_bottom_popup
    }

    override fun onCreate() {
        super.onCreate()
        rvContent = findViewById<RecyclerView>(R.id.rv_content)
        viewTop = findViewById<View>(R.id.view_top)
        viewBottom = findViewById<View>(R.id.view_bottom)
        vSumbit = findViewById<View>(R.id.v_sumbit)
        tvSubmit = findViewById<TextView>(R.id.tv_submit)
        tvPeroidTab = findViewById<TextView>(R.id.tv_peroid_tab)
        tvCategoryTab = findViewById<TextView>(R.id.tv_category_tab)
        tvPro = findViewById<TextView>(R.id.tv_pro)
        tvNext = findViewById<TextView>(R.id.tv_next)
        viewPeroidTab = findViewById<View>(R.id.view_peroid_tab)
        viewCategoryTab = findViewById<View>(R.id.view_category_tab)
        mLlCategory = findViewById<LinearLayout>(R.id.ll_category)
        mViewShadow = findViewById<ShadowLayout>(R.id.view_shadow)
        wheelLinkage = findViewById<LinkageWheelLayout>(R.id.wheel_linkage)

        tvPeroidTab?.setOnClickListener(this)
        tvCategoryTab?.setOnClickListener(this)
        tvNext?.setOnClickListener(this)
        tvPro?.setOnClickListener(this)
        vSumbit?.setOnClickListener(this)
        findViewById<ImageView>(R.id.iv_close).setOnClickListener { dismiss() }
        findViewById<LinearLayout>(R.id.ll_more_category).setOnClickListener {
            mOnPopSwitchListener?.onClick(0, 0)
        }

        initView()
        initEvnet()
    }


    override fun onShow() {
        super.onShow()
        initData()

    }

    private fun initView() {
        mWheelTemPosition1 = mWheelPosition1
        mWheelTemPosition2 = mWheelPosition2
        mProvince = mAllBeans?.get(mWheelPosition1)?.name ?: ""
        mPeriod = YgxToolsKt.getPeriod(
            mAllBeans?.get(mWheelPosition1)?.telSecondCategories?.get(
                mWheelPosition2
            )?.name ?: ""
        )
        val thirdLikeProvider = ThirdLikeProvider(mAllBeans)
        wheelLinkage?.setData(thirdLikeProvider)

        wheelLinkage?.setDefaultValue(mWheelPosition1, mWheelPosition2, 0)
        wheelLinkage?.thirdWheelView?.visibility = View.GONE
        initAdapter()
        initData()

        initEnable()
    }

    private fun initAdapter() {
        val gridLayoutManager = GridLayoutManager(context, 5)
        rvContent?.layoutManager = gridLayoutManager
        mAdapter = CardCategoryImageBottomAdapter(mCategorys)
        rvContent?.adapter = mAdapter
    }

    private fun initData() {
        maxSelected = if (mIsOpen) MAXA_SELECTED else 1
        mAllCategory?.let {
            mCategorys.clear()
            mCategorys.addAll(mAllCategory)
        }
        mSelectedCategorys.clear()
        selectedCategorys?.let {
            mSelectedCategorys.addAll(selectedCategorys)
        }
        for (i in 0 until mCategorys.size) {
            val id = mCategorys[i].fcaid
            val secaid = mCategorys[i].secaid
            mCategorys[i].isSelcted = false
            for (j in 0 until mSelectedCategorys.size) {
                val id1 = mSelectedCategorys[j].fcaid
                val secaid1 = mSelectedCategorys[j].secaid
                if (id == id1 && secaid1 == secaid) {
                    mPosition = i
                    mCategorys[i].isSelcted = true
                    break
                }
            }
        }
        mAdapter?.notifyDataSetChanged()
    }

    private fun initEnable() {
//        val mSelectedCategorys =
//            mCategorys.filter { item -> (!item.isItemHeader) && item.isSelcted }
        if (CollectionUtils.isNotEmpty(mSelectedCategorys)) {
            tvSubmit?.alpha = 1.0f
            vSumbit?.isClickable = true
        } else {
            tvSubmit?.alpha = 0.6f
            vSumbit?.isClickable = false
        }
    }


    private fun initEvnet() {

        viewTop?.setOnClickListener {
            dismiss()
        }

        wheelLinkage?.setOnLinkageSelectedListener { first, second, third ->
            mWheelPosition1 = wheelLinkage?.firstWheelView?.currentPosition ?: 0
            mWheelPosition2 = wheelLinkage?.secondWheelView?.currentPosition ?: 0
            mProvince = mAllBeans?.get(mWheelPosition1)?.name ?: ""
            mPeriod = YgxToolsKt.getPeriod(
                mAllBeans?.get(mWheelPosition1)?.telSecondCategories?.get(
                    mWheelPosition2
                )?.name ?: ""
            )
//            mWheelPosition3 = wheelLinkage?.thirdWheelView?.currentPosition ?: 0
//            mBinding.tvSearchCategory.text =
//                "${mAllBeans!![mWheelPosition1].name}-${mAllBeans[mWheelPosition1].telSecondCategories!![mWheelPosition2].name}"
        }

        mAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            val selected = !data.isSelcted
            if (selected) {
                if (maxSelected == 1) {
                    mSelectedCategorys.clear()
                    if (mPosition == -1) {
                        mCategorys[position].isSelcted = selected
                        mAdapter?.notifyItemChanged(position, R.id.iv_image_tag)
                        mSelectedCategorys.add(data)
                    } else {
                        mCategorys[mPosition].isSelcted = !selected
                        mAdapter?.notifyItemChanged(mPosition, R.id.iv_image_tag)
//                        mSelectedCategorys.remove(mCategorys[mPosition])
                        mSelectedCategorys.add(data)
                        mCategorys[position].isSelcted = selected
                        mAdapter?.notifyItemChanged(position, R.id.iv_image_tag)
                    }
                    mPosition = position
                } else {
                    if (mSelectedCategorys.size < maxSelected) {
                        mCategorys[position].isSelcted = selected
                        mAdapter?.notifyItemChanged(position, R.id.iv_image_tag)
                        mSelectedCategorys.add(data)
                        mPosition = position
                    } else {
                        showToast("最多只能选择${maxSelected}个分类")
                    }
                }

            } else {
                mCategorys[position].isSelcted = selected
                mAdapter?.notifyItemChanged(position, R.id.iv_image_tag)
                for (k in 0 until mSelectedCategorys.size) {
                    val telSecondCategory = mSelectedCategorys[k]
                    if (data.fcaid == telSecondCategory.fcaid && data.secaid == telSecondCategory.secaid) {
                        mSelectedCategorys.removeAt(k)
                        break
                    }
                }
                if (mSelectedCategorys.size == 0) {
                    mPosition = -1
                }
            }
            initEnable()
        }


    }

    private fun findOnePdAndCa() {

        val paramsMap = mutableMapOf<String, String>()
        paramsMap["cpyid"] = mCpyid ?: ""
        paramsMap["otherid"] = mOtherid ?: ""
        paramsMap["province"] = mProvince
        paramsMap["periods"] = mPeriod
        lifecycleScope.launchWhenCreated {
            this.launch {
                val result: DataResult<BaseYgxRsp>? =
                    myScope.async {
                        viewModel?.findOnePdAndCa(paramsMap)
                    }.await()
                result?.let {
                    parseOnePdAndCaResult(result)
                }
            }
        }
    }

    private fun parseOnePdAndCaResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<CategoryPeriodsDataBean> { code, data, message, result ->
                if (code == "200") {
                    selectedCategory()
                }

            }
            onBizError<CategoryPeriodsDataBean> { code, message, data ->
                showToast(message)
            }
        }
    }

    private fun setDismissDialog() {
        dismiss()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

    override fun beforeDismiss() {
        super.beforeDismiss()


    }


    fun setOnSwitchListener(onPopSwitchListener: OnPositionTListener<Int>?) {
        this.mOnPopSwitchListener = onPopSwitchListener
    }

    fun setOpen(isOpen: Boolean) {
        mIsOpen = isOpen
        maxSelected = if (mIsOpen) MAXA_SELECTED else 1
        if (!mIsOpen) {
            for (i in 0 until mCategorys.size) {
                val TelSecondCategory = mCategorys[i]
                if ((!TelSecondCategory.isItemHeader) && TelSecondCategory.isSelcted) {
                    mCategorys[i].isSelcted = false
                    mAdapter?.notifyItemChanged(i, R.id.iv_image_tag)
                }
            }
//            val mSelectedCategorys =
//                mCategorys.filter { item -> (!item.isItemHeader) && item.isSelcted }
            if (mSelectedCategorys.isNotEmpty()) {
                val TelSecondCategory1 = mSelectedCategorys[0]
                val fcaid = TelSecondCategory1.fcaid
                val secaid1 = TelSecondCategory1.secaid
                mPosition = -1
                for (i in 0 until mCategorys.size) {
                    val id = mCategorys[i].fcaid
                    val secaid = mCategorys[i].secaid
//                    if (TelSecondCategory1.id == mCategorys[i].id) {
                    if (fcaid == id && secaid1 == secaid) {
                        mPosition = i
                        mCategorys[mPosition].isSelcted = true
                        mAdapter?.notifyItemChanged(mPosition, R.id.iv_image_tag)
                    }
                }

                mSelectedCategorys.clear()
                mSelectedCategorys.add(TelSecondCategory1)
            }
        }
//        onPopSureListener?.onClick(mWheelPosition1, mWheelPosition2, data = mSelectedCategorys)

//        mSelectedCategorys.clear()
//        if (mPosition != -1) {
//            mSelectedCategorys.add(mCategorys[mPosition])
//        }
        initEnable()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_peroid_tab, R.id.tv_pro -> {
                mTab = 0
                viewPeroidTab?.visibility = View.VISIBLE
                viewCategoryTab?.visibility = View.GONE
                mViewShadow?.visibility = View.VISIBLE
                tvNext?.visibility = View.VISIBLE
                mLlCategory?.visibility = View.GONE
                vSumbit?.visibility = View.GONE
                tvSubmit?.visibility = View.GONE
                tvPro?.visibility = View.GONE
            }
            R.id.tv_category_tab -> {
                tabSelected("请先选择期数")
            }
            R.id.tv_next -> {
                tabSelected("省份期数已存在,请勿重复添加")
            }

            R.id.v_sumbit -> {
                onPopSureListener?.onClick(
                    mWheelPosition1,
                    mWheelPosition2,
                    data = mSelectedCategorys
                )
                dismiss()
            }
        }
    }

    private fun tabSelected(toast: String) {
        if (mCpyid.isNullOrEmpty()) {//开户
            if (!mBeans.isNullOrEmpty()) {
                if (!mIsEditro) {//新增
                    initEditorProvince(mBeans, toast)
                } else {
                    if ((mWheelTemPosition1 == mWheelPosition1) && (mWheelTemPosition2 == mWheelPosition2)) {
                        selectedCategory()
                    } else {
                        initEditorProvince(mBeans, toast)
                    }
                }

            } else {
                selectedCategory()
            }

        } else {
            if (!mIsEditro) {//新增要查是否存在，
                findOnePdAndCa()
            } else {//编辑时，修改了省份期数要查是否存在 没有修改不能查
                if ((mWheelTemPosition1 == mWheelPosition1) && (mWheelTemPosition2 == mWheelPosition2)) {
                    selectedCategory()
                } else {
                    findOnePdAndCa()
                }
            }
        }
    }

    private fun initEditorProvince(mBeans: List<CategoryPeriodsBody>, toast: String) {
        var isAdded = false
        for (i in mBeans.indices) {
            val categoryPeriodsBody = mBeans[i]
            val province = categoryPeriodsBody.province
            val periods = YgxToolsKt.getPeriod(categoryPeriodsBody.periods)
            if (
                (province.contains(mProvince) || mProvince.contains(province))
                && (periods.contains(mPeriod) || mPeriod.contains(periods))
            ) {
                showToast(toast)
                isAdded = true
                break
            }
        }
        if (!isAdded) {
            selectedCategory()
        }
    }

    private fun selectedCategory() {
        mTab = 1
        viewPeroidTab?.visibility = GONE
        viewCategoryTab?.visibility = VISIBLE
        mViewShadow?.visibility = GONE
        mLlCategory?.visibility = VISIBLE
        vSumbit?.visibility = VISIBLE
        tvSubmit?.visibility = VISIBLE
        tvPro?.visibility = VISIBLE
        tvNext?.visibility = GONE
    }
}